package com.wxq.rbac.shiro;

import com.wxq.rbac.model.Permission;
import com.wxq.rbac.model.Role;
import com.wxq.rbac.model.User;
import com.wxq.rbac.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从PrincipalCollection获取用户
        User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissionList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        // 从user中将角色取出遍历
        Set<Role> roleSet = user.getRoles();
        // 判断角色不是为空
        if (CollectionUtils.isNotEmpty(roleSet)) {
            // 遍历角色
            for (Role role : roleSet) {
                roleNameList.add(role.getRname());
                // 获取角色权限
                Set<Permission> permissionSet = role.getPermissions();
                // 判断角色对应权限不为空
                if (CollectionUtils.isNotEmpty(permissionSet)) {
                    // 遍历所有权限
                    for (Permission permission : permissionSet) {
                        // 将权限添加到List中
                        permissionList.add(permission.getPname());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        return info;
    }

    // 认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 将authenticationToken强转成UsernamePasswordToken
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 取出username
        String username = usernamePasswordToken.getUsername();
        // 数据库查询出用户信息
        User user = userService.findByUsername(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
    }
}
